package utils

import (
	"bytes"
	"crypto/tls"
	"io"
	"net/http"
	"net/url"
	"time"
)

type MyDefineResponse struct {
	StatusCode   int
	StatusText   string
	ResponseBody []byte
}

// createHTTPClient 创建带代理和超时的HTTP客户端
func createHTTPClient(proxy string, timeout time.Duration) *http.Client {
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	// 设置代理
	if proxy != "" {
		proxyURL, err := url.Parse(proxy)
		if err == nil {
			transport.Proxy = http.ProxyURL(proxyURL)
		}
	}

	return &http.Client{
		Transport: transport,
		Timeout:   timeout,
	}
}

// HttpGet 发送GET请求
func HttpGet(url string, headers map[string]string, data []byte, proxy string, timeout time.Duration) (MyDefineResponse, error) {
	var myResponse = MyDefineResponse{-1, "InitError", nil}
	// 创建请求
	req, err := http.NewRequest("GET", url, bytes.NewReader(data))
	if err != nil {
		return myResponse, err
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 创建HTTP客户端
	client := createHTTPClient(proxy, timeout)

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return myResponse, err
	}
	defer resp.Body.Close()
	myResponse.StatusCode = resp.StatusCode
	myResponse.StatusText = resp.Status
	myResponse.ResponseBody, _ = io.ReadAll(resp.Body)
	return myResponse, nil
}

// HttpPost 发送POST请求
func HttpPost(url string, headers map[string]string, data []byte, proxy string, timeout time.Duration) (MyDefineResponse, error) {
	var myResponse = MyDefineResponse{-1, "InitError", nil}
	// 创建请求
	req, err := http.NewRequest("POST", url, bytes.NewReader(data))
	if err != nil {
		return myResponse, err
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 如果没有指定Content-Type，默认设置为application/json
	if _, ok := headers["Content-Type"]; !ok && len(data) > 0 {
		req.Header.Set("Content-Type", "application/json")
	}

	// 创建HTTP客户端
	client := createHTTPClient(proxy, timeout)

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return myResponse, err
	}
	defer resp.Body.Close()
	myResponse.StatusCode = resp.StatusCode
	myResponse.StatusText = resp.Status
	myResponse.ResponseBody, _ = io.ReadAll(resp.Body)
	return myResponse, nil
}
